package com.lianniu.web.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.lianniu.web.baseService.file.IFileUploadService;

/**
 * @ClassName：FileUploadUtil
 * @Description:图片上传
 * @Author:liufq
 * @Since: 2016年1月8日17:20:45
 * @Version:版本
 */
@Component
public class FileUploadUtil {
  private Logger logger = Logger.getLogger(FileUploadUtil.class);
  @Autowired
  IFileUploadService fileUploadService;

  /**
   * @Description：上传图片
   * @Param:file req location hidfilepath
   * @Return:图片新路径
   * @Author:liufq
   * @Date:2016年1月8日17:07:26
   */
  public synchronized String getPath(MultipartFile file, HttpServletRequest req, String location,
      String hidfilepath) {

    try {
      logger.info("param check and transfer begin.");
      if (file == null || req == null || StringUtils.isBlank(location)) {
        logger.error("param check and transfer error:");
        return hidfilepath;
      }
      logger.info("param check and transfer end.");
    } catch (Exception e) {
      logger.error("param check and transfer error:" + e.getMessage());
    }

    List<String> fileType = new ArrayList<String>();
    String webpicPath = "";
    try {
      logger.info("List<String> add begin.");
      fileType.add("jpg");
      fileType.add("jpeg");
      fileType.add("bmp");
      fileType.add("gif");
      fileType.add("png");
      fileType.add("xls");
      fileType.add("xlsx");
      logger.info("List<String> add end.");
    } catch (Exception e) {
      logger.error("List<String> fileType:" + e.getMessage());
    }
    try {
      logger.info("fileUploadMulti  begin.");
      if (!StringUtils.isBlank(file.getOriginalFilename())) {
        String filetype = CheckFile(file, fileType);
        if (filetype != "fileok") {
          return filetype;
        }

        webpicPath =
            this.getPath(file.getBytes(), req, file.getOriginalFilename(), location);
      } else {
        webpicPath = hidfilepath;
      }
      logger.info("fileUploadMulti  end.");
    } catch (IOException e) {
      logger.error("fileUploadMulti error:" + e.getMessage());
    }
    return webpicPath;
  }

  /**
   * @Description：检查文件
   * @Param:file fileTypes
   * @Return:01(类型有误) 02(图片大小不得超过1M) fileok
   * @Author:liufq
   * @Date:2016年1月8日17:01:18
   */
  private String CheckFile(MultipartFile file, List<String> fileTypes) {

    try {
      logger.info("param check and transfer begin.");
      if (file == null) {
        throw new Exception("NullPointerException");
      }
      if (fileTypes == null) {
        throw new Exception("NullPointerException");
      }
      logger.info("param check and transfer begin.");
    } catch (Exception e) {
      logger.error("param check and transfer error:" + e.getMessage());
    }
    try {
      logger.info(" filesize and fileTypes begin.");
      long filesize = file.getSize();
      String fileName = file.getOriginalFilename();
      String ext = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
      if (!fileTypes.contains(ext.toLowerCase())) {
        logger.info("图片类型有误！");
        return "01";
      }
      if (filesize >= 1024 * 1024) {
        logger.info("图片大小不得超过1M");
        return "02";
      }
      logger.info(" filesize and fileTypes end.");
    } catch (Exception e) {
      logger.error("filesize and fileTypes error:" + e.getMessage());
    }

    return "fileok";
  }

  /**
   * @Description：返回文件新路径
   * @Param:file req location
   * @Return:新路径
   * @Author:liufq
   * @Date:2016年1月8日17:05:08
   */
  public String getPath(MultipartFile file, HttpServletRequest req, String location) {

    try {
      logger.info("param check and transfer begin.");
      if (file == null) {
        throw new Exception("NullPointerException");
      }
      if (req == null) {
        throw new Exception("NullPointerException");
      }
      logger.info("param check and transfer begin.");
    } catch (Exception e) {
      logger.error("param check and transfer error:" + e.getMessage());
    }

    String picPath = "";
    List<String> fileType = new ArrayList<String>();
    try {
      logger.info("List<String> add begin.");
      fileType.add("jpg");
      fileType.add("jpeg");
      fileType.add("bmp");
      fileType.add("gif");
      fileType.add("png");
      fileType.add("xls");
      fileType.add("xlsx");
      logger.info("List<String> add end.");
    } catch (Exception e) {
      logger.error("List<String> fileType  error:" + e.getMessage());
    }
    try {
      logger.info("fileUploadMulti begin.");
      if (!StringUtils.isBlank(file.getOriginalFilename())) {
        String filetype = CheckFile(file, fileType);
        if (filetype != "fileok") {
          return filetype;
        }

        picPath = this.getPath(file.getBytes(), req, file.getOriginalFilename(), location);

      }
      logger.info("fileUploadMulti end.");
    } catch (IOException e) {
      logger.error("fileUploadMulti error:" + e.getMessage());
    }
    return picPath;
  }
  public String getPath(byte[] bytes,HttpServletRequest req,String fileName,String fileURL){
		String picPath=fileUploadService.fileUploadByte(req.getServerName(), 
					req.getSession().getServletContext().getRealPath("/"), fileName,fileURL, bytes);
		return picPath;
	}
  /**
   * @Description：获取图片服务器上文件的byte数组
   * @Param:request picPath
   * @Return:byte数组
   * @Author:liufq
   * @Date:2016年1月8日17:06:04
   */
  public byte[] getRemoteFileByte(HttpServletRequest request, String picPath) {
    try {
      logger.info("param check and transfer begin.");
      if (request == null) {
        throw new Exception("NullPointerException");
      }
      logger.info("param check and transfer end.");
    } catch (Exception e) {
      logger.error("param check and transfer error:" + e.getMessage());
    }
    return fileUploadService.getRemoteFile(request.getServerName(), request.getSession()
        .getServletContext().getRealPath("/"), picPath);
  }
}
